package com.beiding.hotcode.v2;

class MyOrderedClassLoader extends ClassLoader {

//    private MapClassLoader mapClassLoader;

    private ClassLoader[] parents;

    //给定多个父类加载器
    MyOrderedClassLoader( ClassLoader... parents) {
        this.parents = parents;
    }

    //  Map<String, Class> loadedClassesMap = new HashMap<>();

    //加载类的时候按照先后顺序,将第一个父类加载器加载到结果返回
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {

       System.out.println("加载:" + name);

  /*      Class<?> aClass = mapClassLoader.loadClass(name);
        if (aClass != null) {
            return aClass;
        }
*/
        for (ClassLoader parent : parents) {
            try {
                return parent.loadClass(name);
            } catch (ClassNotFoundException ignore) {

            }
        }
        // return super.loadClass(name);

        return Thread.currentThread().getContextClassLoader().loadClass(name);
        //   return this.getClass().getClassLoader().loadClass(name);
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        System.out.println("加载:" + name + " " + resolve);
        return super.loadClass(name, resolve);
    }

    /*
        对类文件进行局部载入,不需要重复定义
     */

    /*
    void define(ClassFileHolder classFileHolder) {

        classFileHolder.classMap.clear();

        byte[] data = classFileHolder.getMainData();
        Class<?> defineClass = defineClass(null, data, 0, data.length);
        classFileHolder.classMap.put(defineClass.getName(), defineClass);
        List<byte[]> aboutClassData = classFileHolder.getAboutClassData();

        *//*
            问题:
                一个类中有多个内部类,且这些内部类存在集成关系,
                如果子类早于父类加载就会出现无法访问父类的异常

                并且由于在加载子类的时候需要加载父类,因此就会加载到错误的父类

         *//*
        for (byte[] aboutClassDatum : aboutClassData) {
            try {
                Class<?> aClass = defineClass(null, aboutClassDatum, 0, aboutClassDatum.length);
                classFileHolder.classMap.put(aClass.getName(), aClass);
                System.out.println("加载内部类:"+aClass.getName());

            } catch (Throwable throwable) {

                throwable.printStackTrace();

            }

        }

        mapClassLoader.put(classFileHolder);
    }
*/
}
